<template>
  <div id="userManage">
    <div style="margin: 20px 0 ">
      <a-flex justify="space-between">
        <!--   标题   -->
        <h2 style="font-weight: bold">用户管理</h2>
      </a-flex>
    </div>
    <!--  搜索表单区域  -->
    <!-- 搜索表单区域：调整滚动容器和 nowrap 逻辑 -->
    <div class="search-form">
      <!-- 新增滚动容器，负责横向滚动 -->
      <div class="form-scroll">
        <a-form layout="inline" :model="searchParams" @finish="doUserSearch">
          <a-row :wrap="false">
            <a-col flex="auto">
              <a-form-item label="账号">
                <a-input
                  v-model:value="searchParams.userAccount"
                  placeholder="请输入账号"
                  allow-clear
                >
                  <template #prefix>
                    <StarOutlined />
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col flex="auto">
              <a-form-item label="用户名">
                <a-input
                  v-model:value="searchParams.userName"
                  placeholder="请输入用户名"
                  allow-clear
                >
                  <template #prefix>
                    <UserOutlined />
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col flex="240px">
              <a-form-item label="角色">
                <a-select v-model:value="searchParams.userRole" placeholder="请选择角色" allow-clear>
                  <template #suffixIcon>
                    <SmileOutlined />
                  </template>
                  <a-select-option value="admin">管理员</a-select-option>
                  <a-select-option value="user">普通用户</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col flex="auto">
              <a-form-item>
                <a-button type="primary" html-type="submit"> 查询 </a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>

    <!--  用户表格展示区域  -->
    <a-table
      :columns="columns"
      :data-source="userList"
      :pagination="pagination"
      @change="doTableChange"
      :scroll="{ x: 'max-content' }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'userAvatar'">
          <a-image class="user-avatar" :src="record.userAvatar" :width="28" />
        </template>
        <template v-else-if="column.dataIndex === 'userRole'">
          <a-tag v-if="record.userRole === 'user'" color="green">普通用户</a-tag>
          <a-tag v-if="record.userRole === 'admin'" color="blue">管理员</a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button type="primary" danger ghost @click="doDeleteUser(record.id)">删除</a-button>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { deleteUserUsingPost, listUserVoByPageUsingPost } from '@/api/userController'
import { UserOutlined, StarOutlined, SmileOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'

// 定义表头（dataIndex为数据库中的字段信息）
const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    resizable: true,
    ellipsis: true,
    width: 160,
    align: 'center',
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    resizable: true,
    ellipsis: true,
    align: 'center',
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    ellipsis: true,
    align: 'center',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    ellipsis: true,
    align: 'center',
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
    ellipsis: true,
    align: 'center',
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
    ellipsis: true,
    width: 120,
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    ellipsis: true,
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    ellipsis: true,
    align: 'center',
  },
]

// 定义数据源
const userList = ref<API.UserVO[]>([])
const total = ref(0)

// 定义查询参数
const searchParams = reactive<API.UserQueryDTO>({
  current: 1,
  pageSize: 8,
  // 排序条件
  // sortField: 'createTime',
  // sortOrder: 'descend',
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 8,
    total: total.value,
    showSizeChanger: true,
    showTotal: () => `共 ${total.value} 条`,
  }
})

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 调用api，向后端请求数据
const fetchData = async () => {
  const res = await listUserVoByPageUsingPost({
    ...searchParams,
  })
  if (res.data?.code === 0 && res.data?.data) {
    userList.value = res.data?.data?.records || []
    total.value = res.data?.data?.total || 0
  } else {
    message.error('数据获取失败')
  }
}

// 定义钩子函数，页面挂载时加载数据
onMounted(() => {
  fetchData()
})

// 提交表单的搜索处理
const doUserSearch = async () => {
  // 重置页码(重要)
  searchParams.current = 1
  await fetchData()
}

// 删除用户
const doDeleteUser = async (id: number) => {
  if (!id) {
    return
  }
  const res = await deleteUserUsingPost({ id })
  if (res.data?.code === 0 && res.data.data) {
    message.success('删除成功')
    // 重新加载数据
    await fetchData()
  } else {
    message.error('删除失败' + res.data?.message)
  }
}
</script>
<style scoped>
#userManage {
  padding:  10px 30px;
}

.search-form {
  margin-bottom: 24px;
}

/* 新增滚动容器样式：让表单行可横向滚动 */
.form-scroll {
  overflow-x: auto;
  min-width: 600px; /* 最小宽度，避免过窄 */
  white-space: nowrap; /* 确保内部元素不换行（配合 flex-nowrap 更保险） */
}

.user-avatar {
  /* 图片自适应容器，避免拉伸 */
  object-fit: cover; /* 优先保持比例裁剪图片，适合头像/Logo */
  /* 或使用 object-fit: contain; 保持完整显示，可能留空白 */
  border-radius: 50%; /* 核心：将正方形容器转为圆形 */
  overflow: hidden; /* 隐藏超出圆形区域的图片部分 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); /* 可选：添加阴影增强立体感 */
}
</style>
